package com.jingyanzi.finance.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.jingyanzi.finance.domain.CashRefundDO;
import com.jingyanzi.finance.factory.FinanceFactory;

public class VoucherUtil {
	
	private static String tempatePath = "d:/bill.pdf";
	
	private static String savePdfPath = "d:/doc/";
	
	public static String[] pdfBillKey = {"voucherNO","businessNO","name","tel","store","salse","orderNO","billTypeName","amount","payAmount","cashierName","place","cashierDate"};
	
	public static void initPath() {
		Properties properties = new Properties();
		InputStream in = FinanceFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		tempatePath = properties.getProperty("pdf.template.path");
		savePdfPath = properties.getProperty("pdf.save.path");
		System.out.println(tempatePath + ":" + savePdfPath); 
	}

	public static boolean createCasher(Map<String, String> items) {
		//initPath();
		PdfReader reader = null;  
        FileOutputStream out = null;  
        ByteArrayOutputStream bos = null;  
        PdfStamper stamper = null;
        try {
        	savePdfPath = savePdfPath + items.get("businessNO") + ".pdf";
        	
	        out = new FileOutputStream(savePdfPath);// 输出流  
	        reader = new PdfReader(tempatePath);// 读取pdf模板  
	        bos = new ByteArrayOutputStream();  
	        stamper = new PdfStamper(reader, bos);  
	        AcroFields form = stamper.getAcroFields();
	        for(String key : pdfBillKey) {
	        	form.setField(key, items.get(key));
	        }
	        stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true  
            stamper.close();  
  
            Document doc = new Document();  
            PdfCopy copy = new PdfCopy(doc, out);  
            doc.open();  
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);  
            copy.addPage(importPage);  
            doc.close();  
        } catch (Exception e) {
        	e.printStackTrace();
        }
		return true;
	}
	
	public static boolean createRefund(CashRefundDO domain) {
		return true;
	}
	
	public static void main(String[] args) {
		VoucherUtil.createCasher(null);
	}
}
